interface MercatorFace {
  x: number;
  y: number;
}
interface LonlatFace {
  lon: number;
  lat: number;
}



// 墨卡托转经纬度
export const mercatorTolonlat = (mercator: MercatorFace) => {
  let lonlat = { lon: 0, lat: 0 };
  let x = (mercator.x / 20037508.34) * 180;
  let y = (mercator.y / 20037508.34) * 180;
  y =
    (180 / Math.PI) *
    (2 * Math.atan(Math.exp((y * Math.PI) / 180)) - Math.PI / 2);
  lonlat.lon = x;
  lonlat.lat = y;
  return lonlat;
};





// 经纬度转墨卡托

export const lonlatToMercator = (lonLat: LonlatFace) => {
  var mercator = {};
  let x = (lonLat.lon * 20037508.34) / 180;
  let y =
    Math.log(Math.tan(((90 + lonLat.lat) * Math.PI) / 360)) / (Math.PI / 180);
  y = (y * 20037508.34) / 180;
  mercator.x = x;
  mercator.y = y;
  return mercator;
};

export function computeSignedArea(path) {
  //传入 path：{[{lat:,lng:}],[{lat:,lng:}],[{lat:,lng:}]
  let radius = 6371009;
  let len = path.length;
  if (len < 3) return 0;
  let total = 0;
  let prev = path[len - 1];

  let prevTanLat = Math.tan((Math.PI / 2 - (prev.lat / 180) * Math.PI) / 2);
  let prevLng = (prev.lon / 180) * Math.PI;
  for (let i in path) {
    let tanLat = Math.tan((Math.PI / 2 - (path[i].lat / 180) * Math.PI) / 2);

    let lon = (path[i].lon / 180) * Math.PI;

    total += polarTriangleArea(tanLat, lon, prevTanLat, prevLng);

    prevTanLat = tanLat;
    prevLng = lon;
  }
  return Math.abs(total * (radius * radius));
}
function polarTriangleArea(tan1, lng1, tan2, lng2) {
  let deltaLng = lng1 - lng2;
  console.log(tan1, lng1, tan2, lng2);
  let t = tan1 * tan2;
  return 2 * Math.atan2(t * Math.sin(deltaLng), 1 + t * Math.cos(deltaLng));
}
